package com.koron.css2.baseConfig.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.bean.BaseDmaAreaBean;
import com.koron.css2.baseConfig.bean.query.BaseDmaAreaQueryBean;
import com.koron.css2.baseConfig.mapper.BaseDmaAreaMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.TreeBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.util.Constant;
import com.koron.util.JsonUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.swan.bean.MessageBean;

import java.util.List;

/**
 * DMA 分区列表树接口
 */
public class BaseDmaAreaTree implements ServerInterface {

    private static Logger logger = LoggerFactory.getLogger(BaseDmaAreaTree.class);
    @Override
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        MessageBean<TreeBean> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", TreeBean.class);
        try {
            BaseDmaAreaMapper mapper = factory.getMapper(BaseDmaAreaMapper.class);
            BaseDmaAreaQueryBean selectBean = JsonUtils.objectToPojo(req.getData(), BaseDmaAreaQueryBean.class);
            List<BaseDmaAreaBean> list = mapper.selectBaseDmaAreaList(selectBean);
            TreeBean treeBean = new TreeBean();
            // 创建根目录
            treeBean.setId("0");
            treeBean.setCode("");
            treeBean.setName("根目录");
            treeBean.setParent("");
            treeBean.setIsParent(true);
            // 递归下级目录
            recTree(list, treeBean);
            info.setCode(Constant.MESSAGE_INT_SUCCESS);
            info.setDescription("success");
            info.setData(treeBean);

        } catch (Exception e) {
            // TODO: handle exception
            logger.error("查询失败", e);
            return MessageBean.create(Constant.MESSAGE_INT_FAIL, "查询失败", void.class);
        }
        return info;
    }

    /**
     * 递归查询下级目录树
     *
     * @param list
     * @param treeBean
     */
    private void recTree(List<BaseDmaAreaBean> list, TreeBean treeBean) {
        for (BaseDmaAreaBean bean : list) {
            // 如果parentId=父级id，，说明这是他的下级
            if (treeBean.getId().equals(bean.getParentid())) {
                TreeBean b = new TreeBean();
                b.setId(bean.getId() + "");
                b.setCode(bean.getDmaAreaNo());
                b.setParent(treeBean.getId());
                b.setName(bean.getDmaAreaName());
                b.setIsParent(false);
                treeBean.setIsParent(true);
                treeBean.getChildren().add(b);
                recTree(list, b); // 递归循环下级目录
            }
        }
    }

}
